<?php
namespace app\user\model\user;

use app\common\model\BaseModel;
use app\user\logic\user\Account as User;

/**
 * 消息通知模型
 */
class SystemNotify extends BaseModel
{

    /**
     * 表名
     * @var string
     */
    protected $name = 'system_notify';

    /**
     * 设置自动写入时间
     * @var boolean
     */
    protected $autoWriteTimestamp = true;

    /**
     * 定义字段类型
     * @var array
     */
    protected $type = [
        'id'            => 'integer',
        'create_time'   => 'integer',
    ];

/* 查询范围 */

    public function scopeUnread($query, $type = 0)
    {
        if ($type == 1) {       // 系统类
            $query->where('notify_type', 0);
        } else if ($type == 2) {// 课程类
            $query->where('notify_type', 1);
        }

        $query->where('user_id', request()->mid);
        $query->where('is_read', 0);
    }

    public function scopeCourseList($query, $is_read = 2)
    {
        $query->where('user_id', request()->mid)->where('notify_type', 1);
        if ( in_array($is_read, [0,1]) ) {
            $query->where('is_read', $is_read);
        }
    }

    public function scopeSystemList($query, $is_read = 2)
    {
        $query->where('user_id', request()->mid)->where('notify_type', 0);
        if ( in_array($is_read, [0,1]) ) {
            $query->where('is_read', $is_read);
        }
    }

/* 关联 */

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id')->bind([
            'nick_name', 'avatar_url'
        ]);
    }
}
